/// <reference path="../types.ts" />
/// <reference path="../helpers.ts" />
/// <reference path="organization.ts" />
/// <reference path="retrievemultiple.ts" />

module $Xrm.Messages {
    export class RetrieveRequest extends OrganizationRequest {
        public Target: EntityReference;
        public ColumnSet: any; // can be true or array of columns (true = all columns)

        constructor(target?: EntityReference, columnSet?: any) {
            super("Retrieve");

            this.Target = target;
            this.ColumnSet = columnSet;
        }

        GetResponse(responseXml: Document): RetrieveResponse {
            return new RetrieveResponse(responseXml);
        }

        ToSoapXml(): string {
            this.Parameters["Target"] = this.Target;
            this.Parameters["ColumnSet"] = this.ColumnSet;

            return super.ToSoapXml();
        }
    }

    export class RetrieveResponse extends OrganizationResponse {
        public Entity: Entity;

        constructor(responseXml?: Document) {
            super("Retrieve", responseXml);

            this.ParseResponse(responseXml);
            this.BindProperties();
        }

        BindProperties(): void {
            super.BindProperties();

            this.Entity = this.Results["Entity"];
        }

        // retrieve result is tricky, can't use the standard parser inside organization.ts
        ParseResponse(responseXml: Document): void {
            this.Results = []; // clear the values parsed from the base class

            var rn = _xml.getChildNode(responseXml.firstChild.firstChild.firstChild.firstChild, 'a:Results');
            if (rn != null && rn.firstChild != null) {
                var entities = rn.firstChild;
                if (entities != null && entities.childNodes.length > 1) {
                    var resultsNode = entities.childNodes;

                    var parsed = RetrieveMultipleResponse.ParseResults(resultsNode);
                    if (parsed.length > 1) {
                        this.Results["Entity"] = parsed[1]; // the 1st one has a dummy record due to us reusing retrievemultiple parser
                    }
                }
            }
        }
    }
}